package com.lock.aop.aspect;

import com.lock.aop.annoation.NoRepeatSubmit;
import com.lock.utils.LockUtils;
import com.lock.utils.ServletUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交
 *
 * @author lcf
 */
@Aspect
@Component
public class NoRepeatSubmitAspect {
    @Pointcut("@annotation(noRepeatSubmit)")
    public void pointCut(NoRepeatSubmit noRepeatSubmit) {
    }

    @Around(value = "pointCut(noRepeatSubmit)", argNames = "pjp,noRepeatSubmit")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        //锁定时间
        long lockSeconds = noRepeatSubmit.lockSeconds();

        HttpServletRequest request = ServletUtils.getRequest();

        //此处获取用户标识 todo
        String token = request.getHeader("token");
        String path = request.getServletPath();
        String key = getKey(token, path);

        //加锁
        if (lockSeconds <= 0) {
            LockUtils.lock(key);
        } else {
            LockUtils.lock(key, lockSeconds, TimeUnit.SECONDS);
        }

        // 获取锁成功, 执行进程
        Object result;
        try {
            result = pjp.proceed();
        } finally {
            // 解锁
            LockUtils.unlock(key);
        }

        return result;
    }

    private String getKey(String userId, String path) {
        return userId + path;
    }
}
